package com.xianyun.consumer.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResource;
import cn.hutool.http.HttpResponse;
import com.xianyun.common.model.User;
import com.xianyun.common.service.UserService;
import com.xianyun.rpc.model.RpcRequest;
import com.xianyun.rpc.model.RpcResponse;
import com.xianyun.rpc.serializer.Serializer;
import com.xianyun.rpc.serializer.impl.JdkSerializer;

import java.io.IOException;

/**
 * @author xianYun
 * @version 1.0
 **/
// 用户服务的静态代理，需要构建 Http 请求去调用对应的服务提供者
public class UserServiceProxy implements UserService {

    @Override
    public User getUser(User user) {
        //指定序列化器
        Serializer serializer = new JdkSerializer();
        //构建请求对象

        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();
        byte[] bytes = null;
        try {
            //序列化请求
            bytes = serializer.serialize(rpcRequest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //发送请求
        try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                .body(bytes)
                .execute()){
            //取出响应的数据
            byte[] result = httpResponse.bodyBytes();
            //将响应数据反序列化
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            //从响应对象中拿出 返回的数据
            return (User) rpcResponse.getData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
